package org.example.controller;

import org.example.common.constants.Result;
import org.example.pojo.CardInfo;
import org.example.pojo.TradeInfo;
import org.example.service.CardInfoService;
import org.example.service.TradeInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/trade")
public class TrdeInfoController {

    @Autowired
    private TradeInfoService tradeInfoService;


    @Autowired
    private CardInfoService cardInfoService;

    @GetMapping("/balance")
    public Result getBalance(@RequestParam String cardID) {
        CardInfo card = cardInfoService.getById(cardID);
        if (card == null) {
            return Result.error("未找到对应银行卡信息");
        }
        return Result.success(card.getBalance());
    }


    @PostMapping("/deposit")
    public Result deposit(@RequestBody TradeInfo trade) {
        boolean deposit = tradeInfoService.deposit(trade);

        if (deposit) {
            return Result.success("存款成功");
        } else {
            return Result.error("存款失败");
        }
    }


    @PostMapping("/withdraw")
    public Result<?> withdraw(@RequestParam String cardId, @RequestParam BigDecimal amount) {
        try {
            tradeInfoService.withdraw(cardId, amount);
            return Result.success("取款成功");
        } catch (Exception e) {
            return Result.error("取款失败：");
        }
    }


    @PostMapping("/transfer")
    public Result<?> transfer(@RequestParam String fromCardId,
                              @RequestParam String toCardId,
                              @RequestParam BigDecimal amount) {
        try {
            tradeInfoService.transfer(fromCardId, toCardId, amount);
            return Result.success("转账成功");
        } catch (Exception e) {
            return Result.error("转账失败");
        }
    }


    @PostMapping("/reportLoss")
    public Result<Void> reportLoss(@RequestBody Map<String, String> request) {
        String cardID = request.get("cardID");
        CardInfo card = cardInfoService.getById(cardID);
        if (card == null) {
            return Result.error("卡号不存在");
        }
        if (card.getIsReportLoss() != null && card.getIsReportLoss() == 1) {
            return Result.error("该卡已挂失");
        }

        card.setIsReportLoss(1); // 设置为已挂失
        cardInfoService.updateById(card);
        return Result.success();
    }






}